//
//  SectionsViewController.m
//  DataStatistics
//
//  Created by Kang on 16/3/8.
//  Copyright © 2016年 YTYangK. All rights reserved.
//

#import "SectionsViewController.h"
#import "YJLocalCountryData.h"
#import <SMS_SDK/SMSSDK.h>
#import "ACCustomSearchBar.h"
@interface SectionsViewController () {
    NSMutableData* _data;
    NSMutableArray* _areaArray;
}
@end

@implementation SectionsViewController
@synthesize names;
@synthesize keys;
@synthesize table;
@synthesize search;
@synthesize allNames;

#pragma mark Custom Methods
// 搜索方法
- (void)resetSearch
{
    NSMutableDictionary* allNamesCopy = [YJLocalCountryData mutableDeepCopy:self.allNames];
    self.names = allNamesCopy;
    NSMutableArray* keyArray = [NSMutableArray array];
    [keyArray addObject:UITableViewIndexSearch];
    [keyArray addObjectsFromArray:[[self.allNames allKeys] sortedArrayUsingSelector:@selector(compare:)]];

    self.keys = keyArray;
}

#pragma mark 首字母检索
- (void)HandleSearchForFirstStr:(NSString *)firstStr{
    NSMutableArray* sectionsToRemove = [NSMutableArray array];
    [self resetSearch];
    
    for (NSString* Key in self.keys) {
        NSMutableArray* array = [names valueForKey:Key];
        NSMutableArray* toRemove = [NSMutableArray array];
        for (NSString* name in array) {
            // 不区分大小写
            if (![name.uppercaseString hasPrefix:firstStr.uppercaseString] || ![name.lowercaseString hasPrefix:firstStr.lowercaseString]) {
                 [toRemove addObject:name];
            }
        }
        if ([array count] == [toRemove count])
            [sectionsToRemove addObject:Key];
        [array removeObjectsInArray:toRemove];
    }
    [self.keys removeObjectsInArray:sectionsToRemove];
    [table reloadData];
    
}

#pragma mark 模糊查询
- (void)HandleSearchForTerm:(NSString*)searcherm
{
    NSMutableArray* sectionsToRemove = [NSMutableArray array];
    [self resetSearch];

    for (NSString* Key in self.keys) {
        NSMutableArray* array = [names valueForKey:Key];
        NSMutableArray* toRemove = [NSMutableArray array];
        for (NSString* name in array) {
            if ([name rangeOfString:searcherm options:NSCaseInsensitiveSearch].location == NSNotFound) {
                [toRemove addObject:name];
            }
        }
        if ([array count] == [toRemove count])
            [sectionsToRemove addObject:Key];
        [array removeObjectsInArray:toRemove];
    }
    [self.keys removeObjectsInArray:sectionsToRemove];
    [table reloadData];
}

- (void)setareaArray:(NSMutableArray*)array
{
    _areaArray = [NSMutableArray arrayWithArray:array];
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = RGB(34,40,52,1);
    self.title = NSLocalizedString(@"选择国家", nil);
    CGFloat statusBarHeight = 0;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0) {
        statusBarHeight = 20;
    }
    
    //搜索头部
    ACCustomSearchBar * searchBar = [[ACCustomSearchBar alloc] initWithFrame:CGRectMake(18,statusBarHeight, self.view.frame.size.width - 36, 37)];
    searchBar.delegate = self;
    [self.view addSubview:searchBar];
    
    table = [[UITableView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(searchBar.frame) + 5, self.view.frame.size.width, self.view.bounds.size.height -  CGRectGetMaxY(searchBar.frame) - 70) style:UITableViewStylePlain];
    
    [[UITableViewHeaderFooterView appearance] setTintColor:RGB(40, 51, 67, 1)];
    
    table.backgroundColor = RGB(34,40,52,1);
    table.sectionIndexBackgroundColor = RGB(34,40,52,1);
    [self.view addSubview:table];
    
    table.dataSource = self;
    table.delegate = self;
    search.delegate = self;
    
    
    NSString* path = [[NSBundle mainBundle] pathForResource:NSLocalizedString(@"country", nil) ofType:@"plist"];
    NSDictionary* dict = [[NSDictionary alloc] initWithContentsOfFile:path];
    self.allNames = dict;
    [self resetSearch];
    [table reloadData];
    [table setContentOffset:CGPointMake(0.0, 44.0) animated:NO]; //添加搜索框时
    
    // 右边索引栏的颜色
    table.sectionIndexColor = [UIColor orangeColor];
    
    
    UIBarButtonItem* backIetm = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back"] style:UIBarButtonItemStylePlain target:self action:@selector(backItemClick)];
    self.navigationItem.leftBarButtonItem = backIetm;
    self.navigationItem.hidesBackButton = YES;
    
}

-(void)backItemClick{
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark Table View Data Source Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return [keys count];
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([keys count] == 0)
        return 0;
    NSString* key = [keys objectAtIndex:section];
    NSArray* nameSection = [names objectForKey:key];
    return [nameSection count];
}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    NSUInteger section = [indexPath section];
    NSString* key = [keys objectAtIndex:section];
    NSArray* nameSection = [names objectForKey:key];

    static NSString* SectionsTableIdentifier = @"SectionsTableIdentifier";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:SectionsTableIdentifier];

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:SectionsTableIdentifier];
        cell.backgroundColor = RGB(34,40,52,1);
        
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSString* str1 = [nameSection objectAtIndex:indexPath.row];
    NSRange range = [str1 rangeOfString:@"+"];
    NSString* str2 = [str1 substringFromIndex:range.location];
    NSString* areaCode = [str2 stringByReplacingOccurrencesOfString:@"+" withString:@""];
    NSString* countryNamae = [str1 substringToIndex:range.location];

    cell.textLabel.text = [NSString stringWithFormat:@"%@  +%@", countryNamae,areaCode];
    cell.textLabel.textColor = [UIColor whiteColor];
    return cell;
}

#pragma mark 右侧标题栏
- (NSString*)tableView:(UITableView*)tableView titleForHeaderInSection:(NSInteger)section
{
    if ([keys count] == 0)
        return 0;

    NSString* key = [keys objectAtIndex:section];
    if (key == UITableViewIndexSearch)
        return nil;

    return key;
}
- (NSArray*)sectionIndexTitlesForTableView:(UITableView*)tableView
{
    if (isSearching)
        return nil;
    return keys;
}

#pragma mark TableViewDelegate Methods
- (NSIndexPath*)tableView:(UITableView*)tableView willSelectRowAtIndexPath:(nonnull NSIndexPath*)indexPath
{
    [search resignFirstResponder];
    search.text = @"";
    isSearching = NO;
    [tableView reloadData];
    return indexPath;
}
// 修改头部组的
- (void)tableView:(UITableView*)tableView willDisplayHeaderView:(UIView*)view forSection:(NSInteger)section
{
    view.tintColor = RGB(40, 51, 67, 1);

    UITableViewHeaderFooterView* header = (UITableViewHeaderFooterView*)view;
    [header.textLabel setTextColor:[UIColor whiteColor]];
}

- (NSInteger)tableView:(UITableView*)tableView sectionForSectionIndexTitle:(NSString*)title atIndex:(NSInteger)index
{
    NSString* key = [keys objectAtIndex:index];
    if (key == UITableViewIndexSearch) {
        [tableView setContentOffset:CGPointZero animated:NO];
        return NSNotFound;
    }
    else
        return index;
}
- (void)tableView:(UITableView*)tableView didSelectRowAtIndexPath:(NSIndexPath*)indexPath
{
    
    // 选中后修改文字的颜色
    UITableViewCell *cell =  [tableView cellForRowAtIndexPath:indexPath];
    cell.textLabel.textColor = [UIColor orangeColor];
    
    // 增加辅助视图
    UIImageView * inputView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon-selected"]];
    cell.accessoryView = inputView;
    
    NSUInteger section = [indexPath section];
    NSString* key = [keys objectAtIndex:section];
    NSArray* nameSection = [names objectForKey:key];

    NSString* str1 = [nameSection objectAtIndex:indexPath.row];
    NSRange range = [str1 rangeOfString:@"+"];
    NSString* str2 = [str1 substringFromIndex:range.location];
    NSString* areaCode = [str2 stringByReplacingOccurrencesOfString:@"+" withString:@""];
    NSString* countryName = [str1 substringToIndex:range.location];


    NSLog(@"----countryName %@ ---areaCode %@", countryName, areaCode);
    [self.view endEditing:YES];
    if ([self.delegate respondsToSelector:@selector(setSecondData:)]) {
        [self.delegate setSecondData:@{@"countryName":countryName,@"areaCode":areaCode}];
    }

    [self clickLeftButton];
}

#pragma mark Search Bar Delegate Methods
- (void)textViewDidBeginEditing:(UITextView *)textView{
    [table reloadData];
}

- (void)textViewDidChange:(UITextView *)textView{
    if([textView.text isEqualToString:@"\n"]){
        textView.text = @"";
        return;
    }
    if ([textView.text length] == 0 ) {
        [self resetSearch];
        [table reloadData];
        return;
    }
    [self HandleSearchForFirstStr:textView.text];
}



- (void)clickLeftButton
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void) hidenSearchBarIcon:(UISearchBar *)searchBar{
    
    UITextField *txfSearchField = [searchBar valueForKey:@"_searchField"];
    [txfSearchField setBackgroundColor:[UIColor whiteColor]];
    [txfSearchField setLeftViewMode:UITextFieldViewModeNever];
    [txfSearchField setRightViewMode:UITextFieldViewModeNever];
    txfSearchField.layer.cornerRadius = 10;
    txfSearchField.borderStyle = UITextBorderStyleNone; // 只有当边框类型为None时，设置背景图片才有效果
    [txfSearchField setBackground:[UIImage imageNamed:@"text-search"]];
    txfSearchField.clearButtonMode=UITextFieldViewModeNever;
}


@end
